<template>
  <div>
    <MainNavBar class="main-nav" id="main-nav">
      <template #center-name> 上传视频购买合同 </template>
    </MainNavBar>
    <div class="container">
      <div class="roll"></div>
      <div class="line"></div>
      <div class="main">
        <div class="prove">
          <div class="right">
            <div class="title">上传视频购买合同</div>
            <div class="left_bottom">
              <div class="file" @click="selectfile">
                <div class="header" v-if="!state.prove">
                  <div class="add"></div>
                </div>
                <div class="header" v-else>
                  <img :src="state.prove" alt="上传视频购买合同" />
                </div>
                <input
                  type="file"
                  @change="fileChange"
                  accept="image/png,image/jpg,image/jpeg"
                  style="display: none"
                  ref="file"
                />
              </div>
              <div class="up_tip">
                  应版权方要求，本视频须购买后方可查看或下载。<br>
                点击查看
                <a href="http://qnticao.laigl.com/video/video_page.jpg"
                  >《视频购买合同》</a
                >
                ，保存图片到本地，打印后在乙方处签字后再拍照上传。
              </div>
            </div>
          </div>
        </div>
        <div
          class="goto-sign"
          :class="state.prove == '' || isPaying ? 'noclick' : ''"
          :style="backgroundColor"
          @click="pay"
        >
          确认并支付
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { GetSignature } from "../../utils/wx-sdk.js";
import { BASESHARE } from "../../../setting.js";
import wx from "weixin-js-sdk";
import MainNavBar from "@/components/common/nav/MainNavBar.vue";
import { reactive, ref } from "@vue/reactivity";
import * as qiniu from "qiniu-js";
import { computed, onMounted } from "@vue/runtime-core";
import { Toast } from "vant";
import { request } from "@/network/request";
import { useRoute, useRouter } from "vue-router";
export default {
  components: {
    MainNavBar,
  },
  setup() {
    const state = reactive({
      prove: "",
    });
    const route = useRoute();
    const router = useRouter();
    // 获取文件上传token
    let token = ref("");
    const getQiniuToken = async () => {
      const qn = await request({
        url: "/v1/upload/getToken",
      });
      if (qn.code == 2000) {
        token.value = qn.data;
      }
    };

    // 生成随机视频名称
    const randomWord = (randomFlag, min, max) => {
      var str = "",
        range = min,
        arr = [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "a",
          "b",
          "c",
          "d",
          "e",
          "f",
          "g",
          "h",
          "i",
          "j",
          "k",
          "l",
          "m",
          "n",
          "o",
          "p",
          "q",
          "r",
          "s",
          "t",
          "u",
          "v",
          "w",
          "x",
          "y",
          "z",
          "A",
          "B",
          "C",
          "D",
          "E",
          "F",
          "G",
          "H",
          "I",
          "J",
          "K",
          "L",
          "M",
          "N",
          "O",
          "P",
          "Q",
          "R",
          "S",
          "T",
          "U",
          "V",
          "W",
          "X",
          "Y",
          "Z",
        ];
      // 随机产生
      if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
      }
      for (var i = 0; i < range; i++) {
        let pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
      }
      return str;
    };
    // const currentRate = ref("0%");
    // 上传视频至七牛云
    function upload(file) {
      let toast1 = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: "0%",
      });
      return new Promise((resolve, reject) => {
        let key = randomWord(false, 20);
        var config = {
          useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0, //选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域。  我这里是华东区
          domain: "https://qnticao.laigl.com", //配置好的七牛云域名  如   https://cdn.qniyun.com/
          // max_file_size: "100mb",
          chunkSize: 5, //每个分片的大小，单位mb，默认值3
          forceDirect: false, //直传还是断点续传方式，true为直传
        };
        var putExtra = {
          fname: file.name, //文件原始文件名
          params: {}, //放置自定义变量
          mimeType: "image/png,image/jpg,image/jpeg", //限制上传文件类型
          // mimeType: [] || null, //限制上传文件类型
          // ...config,
        };
        var observable = qiniu.upload(file, key, token.value, putExtra, config);
        observable.subscribe({
          next: (result) => {
            console.log(result);
            //主要用来展示进度
            // currentRate.value = Math.floor(result.total.percent);
            toast1.message = Math.floor(result.total.percent) + "%";
          },
          error: (err) => {
            //上传错误后触发
            // console.log(err);
            // currentRate.value = 0;
            // Toast.clear();
            toast1.clear();
            Toast.fail("照片上传失败");
            return;
          },
          complete: (result) => {
            //上传成功后触发。包含文件地址。
            // if(!prove && !notification){
            //   state.headerimg = URL.createObjectURL(file);
            // }else if(prove){
            //   state.prove = URL.createObjectURL(file);
            // }else if(notification){
            //   state.notification = URL.createObjectURL(file);
            // }
            state.prove = URL.createObjectURL(file);
            toast1.clear();
            Toast.success("照片上传成功");
            resolve(result);
          },
        });
      });
      // });
    }

    const file = ref(null);
    function selectfile() {
      state.prove = "";
      file.value.click();
    }
    const img = ref("");
    async function fileChange(e) {
      const res = await upload(e.target.files[0]);
      img.value = "http://qnticao.laigl.com/" + res.key;
    }
    const isPaying = ref(false);
    function pay() {
      if (isPaying.value == true) return;
      isPaying.value = true;
      GetSignature(BASESHARE, async () => {
        const result = await request({
          url: "v1/ucenter/video_wxPay",
          data: {
            compet_id: route.query.compet_id,
            level_id: route.query.level_id,
            // 价格无论传多少都无所谓  由后端控制
            token: sessionStorage.getItem("token"),
            img: img.value,
          },
        });

        // Toast("v1/ucenter/wxPay没出现错误")
        if (result.code == 2000) {
          // alert("马上调用微信SKD支付")
          // Toast("马上调用微信SKD支付");
          const { appId, nonceStr, paySign, signType, timeStamp } = result.data;
          try {
            // toast.clear();
            wx.chooseWXPay({
              // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。
              // 但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              timestamp: timeStamp,
              // 支付签名随机串，不长于 32 位
              nonceStr: nonceStr,
              package: result.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: paySign, // 支付签名
              success: function (res) {
                // 支付成功后的回调函数
                // console.log(res)
                // Toast("马上调用sign接口");
                isPaying.value = false;
                router.push({
                  path: "/Level3up",
                  query: {
                    compet_id: route.query.compet_id,
                    level_id: route.query.level_id,
                  },
                });
              },
              fail: function (res) {
                // Toast("支付失败");
                isPaying.value = false;
              },
              complete: function (res) {
                // console.log(res, "complete");
                // Toast("支付完成不确定成功");
                isPaying.value = false;
              },
            });
          } catch (error) {
            Toast("sdk调用错误");
            isPaying.value = false;
            // alert(error);
          }
        } else {
          // toast.clear();
          isPaying.value = false;
          Toast(result.msg);
        }
      });
    }
    onMounted(() => {
      Toast.allowMultiple();
      getQiniuToken();
    });
    const backgroundColor = computed(() => {
      if (state.prove == "" || isPaying.value)
        return { backgroundColor: "#ced3e0" };
      else return { backgroundColor: "#0054a6" };
    });
    return { state, selectfile, file, fileChange, backgroundColor, pay };
  },
};
</script>

<style lang="less" scoped>
.noclick {
  pointer-events: none;
}
.container {
  width: 100%;
  min-height: calc(100vh - 13.333vw);
  background-image: url("http://qnticao.laigl.com/vue/profile_bg_big.jpg");
  background-repeat: repeat-y;
  background-color: #0054a6;
  // background-size: cover;
  background-size: 100% auto;
  position: relative;
  overflow: hidden;
  .roll {
    position: absolute;
    left: 11.467vw;
    top: 8.267vw;
    box-sizing: border-box;
    width: 3.2vw;
    height: 3.2vw;
    border-radius: 50%;
    border: 0.533vw solid #ffffff;
  }
  .line {
    position: absolute;
    left: 12.8vw;
    top: 11.467vw;
    width: 0.533vw;
    height: 14.667vw;
    background: #ffffff;
    border-radius: 0.267vw;
  }
  .main {
    width: 100%;
    background-color: #fff;
    min-height: calc(100vh - 16.333vw - 13.333vw);
    border-top-left-radius: 3.2vw;
    border-top-right-radius: 3.2vw;
    -webkit-appearance: none;
    margin-top: 16.333vw;
    overflow: hidden;
  }
  .prove {
    // padding-top: 5.333vw;
    position: relative;
    z-index: 1;
    justify-content: space-between;
    align-items: center;
    width: 88.267vw;
    font-size: 3.2vw;
    margin: 0 auto;
    // height: 100%;
    // padding: 0 4.267vw;
    padding: 30px 0;
    background-color: #f9f9f9;
    color: #ced3e0;
    // box-sizing: border-box;
    .title {
      font-size: 4.267vw;
    }
    .left_bottom {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-evenly;
      // align-items: center;
      a {
        color: #0054a6;
        text-decoration: underline;
      }
      .up_tip {
        width: 40vw;
        line-height: 4.267vw;
        font-size: 3.733vw;
        color: #fccf00;
      }
    }
    .left,
    .right {
      padding-top: 4vw;
      margin: 0 4.533vw;
      .file {
        margin-top: 3.2vw;
        margin-right: 2.667vw;
        width: 37.333vw;
        height: 37.333vw;

        .header {
          width: 100%;
          height: 100%;
          border-radius: 2.667vw;
          background-color: #fff;
          display: flex;
          justify-content: center;
          align-items: center;
          .add {
            //   border: 0.267vw dashed #ccc;
            width: 5.333vw;
            height: 5.333vw;
            background: url("http://qnticao.laigl.com/vue/add.png") center
              no-repeat;
          }
        }
        img {
          width: 100%;
          height: 100%;
          vertical-align: middle;
        }
      }
    }
    .left {
      margin-left: 4.533vw;
      margin-right: 4.533vw;
      .up_tip {
        margin-top: 3.2vw;
      }
    }
    .right {
      margin-top: 4vw;
      .up_tip {
        margin-top: 7.2vw;
      }
    }
  }
  .goto-sign {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 16vw;
    color: #fff;
    border-radius: 5.333vw 5.333vw 0vw 0vw;
    text-align: center;
    line-height: 16vw;
    font-size: 5.6vw;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
  }
}
</style>